import {ref, reactive, onMounted, computed, toRefs} from 'vue'
import {message} from "ant-design-vue";
import {VXETable} from 'vxe-table'
import {MaterialOrderService} from "@/views/restaurant/material/materialOrder/materialOrderService";
// import {SupplyMaterialService} from "@/views/restaurant/material/materialOrder/materialOrderService";


export default function orderMaterialRelationMapMannage(props) {
  let id = 0;
  //vxeTable的映射对象
  const orderMaterialRelationTable = ref({})

  let isDetail = ref(props.isDetail);

  //编辑组件的映射的映射对象
  const editTable = ref({})
  //需要传递给编辑组件的类信息
  let orderMaterialRelationEntityData = reactive({
    name: '',
    supplierName: '',
    supplierId: '',
    todayPrice: '',
    tomorrowPrice: '',
    floatRatio: '',
    faliuresNum: '',
    remark: ''
  });

  //管理列表展示
  let orderMaterialRelationList = ref([]);

  console.log(toRefs(props).materialOrderId.value)
  let business = reactive({materialOrderId: toRefs(props).materialOrderId.value})

  let orderMaterialRelationTemp = ref(props.orderMaterialRelations);

  const tableConfig = {
    border: true,
    showHeaderOverflow: true,
    showOverflow: true,
    resizeable: true,
    keepSource: true,
    highlightHoverRow: true,
    align: "center",

    columns: [
      {
        title: '供应商',
        minWidth: "10%",
        fixed: "left",
        slots: {default: 'supplierName'},
      },
      {
        title: '供应商材料名称',
        minWidth: "10%",
        fixed: "left",
        slots: {default: 'supplyMaterialName'},
      },
      {
        field: 'remark',
        title: '备注',
        minWidth: "10%",
        editRender: {name: 'input', attrs: {type: 'text'}, placeholder: '请点击输入备注'},
      }

    ],

    keyboardConfig: {
      isArrow: true,
      isDel: true,
      isEnter: true,
      isTab: true,
      isEdit: true,
    },

    //表格编辑设置
    editConfig: {
      trigger: 'click',
      mode: 'cell',
      showStatus: true,
      icon: "fa",
    },
    mouseConfig: {
      selected: true
    },
    checkboxConfig: {range: true},

    //todo :表格内容注释设置

    tooltipConfig: {
      showAll: true,
      enterable: true,
    },

    //todo 工具栏
    toolbarConfig: {
      className: 'vxe-toolbar-mt',
      slots: {buttons: 'component_title', tools: 'tool_button'},
      refresh: false,
      import: false,
      export: false,
      print: false,
      zoom: true,
      custom: false
    },

    editRules: reactive({
      name: [
        {required: true, message: '材料名称必须输入', trigger: "onSubmit"},
      ]
    })
  }

  //为只读状态下隐藏操作按钮
  if (!isDetail.value) {
    tableConfig.columns.push({
      title: '操作',
      minWidth: "12%",
      slots: {default: 'operate'},
      fixed: 'right'
    })
  }

  const changeHeight = (tableHeight) => {
    if (tableHeight) {
      tableConfig.height = tableHeight;
    }
  }

  changeHeight(props.height);

  //渲染表格
  onMounted(() => {
    if (orderMaterialRelationTemp.value) {
      orderMaterialRelationChange(orderMaterialRelationTemp.value)
    } else {
      reload(business);
    }
  })

  //页面的重载
  let reload = (business) => {
    console.log(business)
    const conditions = {
      materialOrderId: business.materialOrderId,
    }

    const queryParams = {}
    //获取筛选结果（无懒加载）
    queryParams.filters = conditions
    queryParams.orderBys = [{property: "todayPrice",order: "desc"}]
    //该方法所有语句结束后执行
    console.log(queryParams)
    MaterialOrderService.findOrderMaterialRelations(queryParams).then((res) => {
      orderMaterialRelationChange(res.data.datas)

      //vxetable的data改变，但未渲染到对应的表格中
      // orderMaterialRelationList.value.push({})
      // supplyMaterialChange(orderMaterialRelationList.value)
    }).catch((error) => {
      message.error(error.message);
    })

  }

  //合并新数组到旧数组，新数组全部保留，旧数组只保留新增的部分,即eid为空的对象
  let orderMaterialRelationChange = (orderMaterialRelations) => {
    for (let i = 0; i < orderMaterialRelations.length; i++) {
      orderMaterialRelations[i].id = id++;
      orderMaterialRelations[i] = reactive(orderMaterialRelations[i])
    }

    let list = orderMaterialRelations;
    console.log("当前数组为", orderMaterialRelationList.value)
    for (let i = 0; i < orderMaterialRelationList.value.length; i++) {
      let item = reactive(orderMaterialRelationList.value[i])
      // console.log("item", item)
      if ((item.eid === undefined || item.eid === null) && item.bankorderMaterialRelation !== undefined) {
        item.id = id++
        list.push(item);
      }
    }

    orderMaterialRelationList.value = list;

    console.log("orderMaterialRelationList", list);

  }

  //新增
  const insertEvent = async (row) => {
    orderMaterialRelationEntityData = reactive({
      materialName: '',
      supplierName: '',
      materialOrderId: '',
      materialId:'',
      remark: ''
      // materialOrderId: business.materialOrderId,
      // bank: '',
      // bankAccount: ''
    })
    const $table = orderMaterialRelationTable.value
    const {row: newRow} = await $table.insertAt(orderMaterialRelationEntityData, row)
    await $table.setActiveCell(newRow, 'name')

    //新增数据无法动态添加进代理对象，
    // 需要之后获取对象时通过$table.getInsertRecords()获取所有新增后的对象
    console.log(orderMaterialRelationList.value)

  }

  //移除数据
  const removeEvent = (row) => {
    if (row.eid) {
      MaterialOrderService.deleteOrderMaterialRelation(row.eid).then((res) => {
        console.log("删除的对象为", res);
      }).catch((error) => {
        message.error(error.message);
      })
    }
    for (let i = 0; i < orderMaterialRelationList.value.length; i++) {
      if (orderMaterialRelationList.value[i].id === row.id) {
        orderMaterialRelationList.value.splice(i, 1);
        break;
      }
    }
    const $table = orderMaterialRelationTable.value
    $table.remove(row)
  }

  //修改状态
  /*const changeStatus = (row) => {
    if (row.status === "启用") {
      row.status = "停用"
    } else {
      row.status = "启用"
    }
  }*/


  var orderMaterialRelationMap = reactive({});
  const validAccounts = async () => {
    const $table = orderMaterialRelationTable.value
    console.log("orderMaterialRelationMap", orderMaterialRelationMap)

    orderMaterialRelationMap = reactive({})

    const errMap = await $table.validate(true).catch(errMap => errMap)
    console.log("errorMap", errMap)
    if (errMap) {
      VXETable.modal.message({status: 'error', content: '账户校验不通过！'})
      return false
    } else {
      // VXETable.modal.message({status: 'success', content: '账户校验成功！'})
      return true
    }
  }

  //获取当前列表中的数据，结果为null说明验证失败
  //Todo :表单验证
  const getOrderMaterialRelationList = async () => {
    const $table = orderMaterialRelationTable.value

    orderMaterialRelationMap = reactive({})

    const errMap = await $table.validate(true).catch(errMap => errMap)
    console.log("errorMap", errMap)
    if (errMap) {
      // VXETable.modal.message({status: 'error', content: '账户校验不通过！'})
      return null
    } else {
      let list = orderMaterialRelationTable.value.getInsertRecords();

      orderMaterialRelationList.value.forEach((account) => {
        list.push(account)
      })
      console.log("orderMaterialRelationList", list);
      // VXETable.modal.message({status: 'success', content: '账户校验成功！'})
      return list
    }
  }

  const ratio = computed(()=>{
    return function (row){
      return orderMaterialRelationList.value[row].todayPrice
    }
  })

  /*const test = (rowIndex) =>{
    orderMaterialRelationList.value[rowIndex.rowIndex].floatRatio = computed(()=>{
      return orderMaterialRelationList.value[rowIndex.rowIndex].todayPrice
    })
  }*/

  const countRatio = (row) => {
    if(row.tomorrowPrice===0||!row.tomorrowPrice){
      return '无'
    }else{
      return ((row.todayPrice-row.tomorrowPrice)/row.tomorrowPrice).toFixed(2)
    }
  }

  return {
    tableConfig,
    validAccounts,
    getOrderMaterialRelationList,
    // changeStatus,
    editTable,
    orderMaterialRelationTable,
    orderMaterialRelationList,
    business,
    reload,
    orderMaterialRelationChange,
    insertEvent,
    removeEvent,
    // test,
    ratio,
    countRatio
  }

}

